import { computed, defineComponent, inject, onMounted, ref } from "vue";
import ResetBlockSizeComponent from "../ResetBlockSizeComponent/resetBlockSize";

export default defineComponent({
  props: {
    block: { type: Object },
    handleModelValue: {
      type: Function
    }
  },
  setup(props) {
    const blockStyles = computed({
      get() {
        return {
          width: props.block.config.width ? props.block.config.width + 'px' : 'auto',
          height: props.block.config.height ? props.block.config.height + 'px' : 'auto',
          left: props.block.left + 'px',
          top: props.block.top + 'px',
          zIndex: props.block.index,
          position: 'absolute',
        }

      }
    })
    const config = inject('config')
    const blcokRef = ref(null)
    onMounted(() => {
      const { offsetHeight, offsetWidth } = blcokRef.value
      const handleModelValue = props.handleModelValue
      const tempblock = props.block
      if (tempblock.alignCenter) {
        const left = (tempblock.left - offsetWidth / 2)
        tempblock.left = left > 0 ? left : 0
        const top = (tempblock.top - offsetHeight / 2)
        tempblock.top = top > 0 ? top : 0
        tempblock.alignCenter = false
      }
      tempblock.width = offsetWidth
      tempblock.height = offsetHeight

      handleModelValue({ update: true, updateBlock: tempblock })
    })
    const updateBlock = (block) => {
      props.handleModelValue({ update: true, updateBlock: block })
    }
    return () => {
      const component = config.componentMap[props.block.key]
      const componentRender = component.render({
        config: props.block.config || {},
        reSize: props.block.hasReSize ? { width: props.block.width, height: props.block.height } : {}
      })
      // 当前选中组件是否 可以设置 宽高
      const { width, height } = component.reSize || {}
      return <div class="editor-block" style={blockStyles.value} ref={blcokRef}>
        {componentRender}
        {props.block.foucs && (width || height) && <ResetBlockSizeComponent block={props.block} component={component} updateBlock={updateBlock}></ResetBlockSizeComponent>}
      </div>
    }
  }
})